# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane

require 'json'

## wisher 打包机器人地址
## https://open.feishu.cn/open-apis/bot/v2/hook/6bcba34f-67da-448f-8604-c7380a784f71
## pyg key: 8aa7b3cc1e2bd2be8db1e2dcfb750189



content1111 = "{\"key\":\"value\"}" # 这里是你的JSON内容

# 蒲公英App Key
kPgyAppKey = "8aa7b3cc1e2bd2be8db1e2dcfb750189"
# 飞书API url
kFeishuApiBase = "https://open.feishu.cn/open-apis/bot/v2/hook"
# 飞书开发群token
# kFeishuToken = "88a800f8-1158-42c7-b8d2-9f1dcb3514dd"
# 飞书泡泡糖团队token
kFeishuToken = "6bcba34f-67da-448f-8604-c7380a784f71"


# Android debug apk包路径
kDebugApkPath = "../build/app/outputs/flutter-apk/app-arm64-v8a-debug.apk"

default_platform(:android)

platform :android do
  # desc "Runs all the tests"
  # lane :test do
  #   gradle(task: "test")
  # end

  # desc "Submit a new Beta Build to Crashlytics Beta"
  # lane :beta do
  #   gradle(task: "clean assembleRelease")
  #   crashlytics
  
  #   # sh "your_script.sh"
  #   # You can also use other beta testing services here
  # end

  # desc "Deploy a new version to the Google Play"
  # lane :deploy do
  #   gradle(task: "clean assembleRelease")
  #   upload_to_play_store
  # end

  desc "上传APK到蒲公英, 上报飞书修改日志"
  lane :beta do |options|
    puts "上传蒲公英..."
    upload options
    puts "上传蒲公英 Done"
    puts "生成修改日志，将结果向飞书发送..."
    notify_changeLog options
    puts "生成修改日志，将结果向飞书发送 Done"
  end

  desc "上传蒲公英"
  lane :upload do |options|
    apk = options[:apk] || kDebugApkPath
    puts "apk: #{apk}"
    answer = pgyer(api_key: kPgyAppKey, install_type: "1", apk: apk, update_description: "version: #{options[:version]}")
    puts answer
    # terminal outputs like this if uploaded successfully
    # {"buildKey"=>"xxxx", "buildType"=>"2", "buildIsFirst"=>"0", "buildIsLastest"=>"1", "buildFileKey"=>"xxx.apk", "buildFileName"=>"", "buildFileSize"=>"111111", "buildName"=>"testApk", "buildVersion"=>"0.11.0", "buildVersionNo"=>"13", "buildBuildVersion"=>"10", "buildIdentifier"=>"com.pgyer.testapk", "buildIcon"=>"xxxx", "buildDescription"=>"", "buildUpdateDescription"=>"", "buildScreenshots"=>"", "buildShortcutUrl"=>"xxxxxxx", "buildCreated"=>"2023-04-04 11:33:24", "buildUpdated"=>"2023-04-04 11:33:24", "buildQRCodeURL"=>"https://www.pgyer.com/app/qrcodeHistory/xxxxxx", "fastlaneAddedWholeVisitUrl"=>"https://www.pgyer.com/xxxxxx"}
    puts "url = #{answer["fastlaneAddedWholeVisitUrl"]}"
  
    # terminal outputs like this if uploaded successfully
    # url = https://www.pgyer.com/xxxxxx
  
    # More information please visit https://www.pgyer.com/doc/view/api#fastUploadApp to check API "https://www.pgyer.com/apiv2/app/buildInfo"
  end

  # 根据数量或者上次的commitid决定返回的日志数量
  # 命令: fastlane change_logs count:[number]  # 获取指定数量的修改日志
  # 命令: fastlane change_logs commit:[commit-id]  # 获取指定commit之后的修改日志
  desc "获取修改日志"
  lane :change_logs do |options|
    path = options[:path] || Dir.pwd  # 修改日志所在的路径，默认为当前路径

    # puts "change_logs: path:" + path
    # 如果没有传递参数，则从文件中读取最新的commit ID
    commit = options[:commit] || (File.exist?(File.join(path, ".last-commit")) ? File.read(File.join(path, ".last-commit")).strip : nil)

    # if commit
    #   puts "change_logs: commit:" + commit
    # end

    # 获取最新的commit ID
    Dir.chdir(path) do
      # code here runs in the parent directory
      latest_commit = sh("git rev-parse HEAD").strip
      # puts "change_logs: latest_commit:" + latest_commit
      # 将最新的commit ID写入文件
      File.write(File.join(path, ".last-commit"), latest_commit)
    end

    changelog_options = {
      pretty: "- (%ae) %s",  # 修改日志的格式
      date_format: "short",  # 日期的格式
      match_lightweight_tag: false,  # 是否匹配轻量级标签
      merge_commit_filtering: "exclude_merges",  # 是否过滤合并提交
      path: path  # 修改日志所在的路径
    }

    if options[:count]
      # puts "使用count:" + options[:count]
      changelog_options[:commits_count] = options[:count]  # 获取指定数量的修改日志
    elsif commit
      # puts "使用commit:" + commit
      changelog_options[:between] = [commit, "HEAD"]  # 获取上次commit之后的修改日志
    else
      # puts "使用count == 1"
      changelog_options[:commits_count] = 1  # 默认获取最新的一条修改日志
    end

    changelog_from_git_commits(changelog_options)  # 获取修改日志
  end

  desc "生成修改日志，将结果向飞书发送"
  lane :notify_changeLog do |options|
    content = %Q|
    {
      "title": "flutter_fastlane_demo #{options[:version]} Android 准备测试了:",
      "content": [
        [{
            "tag": "a",
            "href": "https://www.pgyer.com/i38BUG",
            "text": "下载地址"
        }],
    |

    # 添加日志
    options[:content] = content
    getChangeLogs options
    content = options[:content] || ""

    # 结尾
    content += %Q|
      ]
    }
    |
    # puts content
    options[:content] = content
    notify_feishu options
  end



  desc "向飞书发送信息, 信息从输入参数content字段传入"
  lane :notify_feishu do |options|
    content = options[:content]
    puts content
    sh(
      command: %Q[
        curl '#{kFeishuApiBase}/#{kFeishuToken}'  \
        -X 'POST' \
        -H 'Content-Type: application/json' \  
        -d '{ 
          "msg_type": "post",
          "content": {
            "post": {
              "zh_cn": #{content}
              \}
            \}
          \}' 
      ]
    )
  end

  # curl 'https://open.feishu.cn/open-apis/bot/v2/hook/6bcba34f-67da-448f-8604-c7380a784f71' -X POST -H 'Content-Type: application/json' -d '{"msg_type":"post","content":{"post":{"zh_cn":{"title":"通知标题","content":[[{"tag":"text","text":"这里是正文内容"}]]}}}}'


  # 获取修改日志
  # 参数:
  # - options: 选项哈希表，包含以下可选键值对:
  #   - content: 修改日志的内容，默认为空字符串
  #   - logTitle: 修改日志的标题，默认为空字符串
  #
  # 返回值:
  # - 无
  #
  # 功能:
  # 根据选项获取修改日志，并将结果格式化为指定的内容格式。
  desc "获取修改日志"
  lane :getChangeLogs do |options|
    content = options[:content] || ""  # 修改日志所在的路径，默认为当前路径

    logTitle = options[:logTitle] || ""  # 修改日志所在的路径，默认为当前路径

    changeLogs = change_logs options
    puts changeLogs

    # changeLogsArray = changeLogs.split("\n").map { |log| { "tag": "text", "text": log } }
    changeLogsArray = changeLogs.nil? ? [] : changeLogs.split("\n").map { |log| { "tag": "text", "text": log } }
    # puts changeLogsArray 

    if changeLogsArray.empty?
      content += %Q|
        [
          {
            "tag": "text",
            "text": "#{logTitle}无修改"
          }
        ]
      |
    else
      content += %Q|
        [
          {
            "tag": "text",
            "text": "#{logTitle}修改日志:"
          }
        ],
      |
      changeLogsArray.each_with_index do |log, index|
        content += %Q|
          [
            {
              "tag": "#{log[:tag]}",
              "text": "#{log[:text]}"
            }
          ]
        |
        if index != changeLogsArray.length - 1
          content += ","
        end
      end
    end
    # puts content 
    options[:content] = content
  end
end

# error block is executed when a error occurs
error do |lane, exception|
  puts exception.to_s
end
